package config

import (
	"gitee.com/ktark/ktark-framework/ktark-core/cmap"
)

// ==================
// config-bean_definition_registry: bean定义注册表
// ==================

// BeanDefinitionRegistry bean 定义注册表
type BeanDefinitionRegistry interface {
	// RegisterBeanDefinition 注册bean定义
	RegisterBeanDefinition(string, BeanDefinition)
	// RemoveBeanDefinition 移除bean定义
	RemoveBeanDefinition(string) *BeanDefinition
	// GetBeanDefinition 获取bean定义
	GetBeanDefinition(string) *BeanDefinition
	// ContainsBeanDefinition 是否包含bean定义
	ContainsBeanDefinition(string) bool
	// IsBeanDefinitionOverridable bean定义是否可以重写
	IsBeanDefinitionOverridable(string) bool
	// IsBeanNameInUse bean name 是否被使用
	IsBeanNameInUse(string) bool
	// GetBeanDefinitionNames 获取全部 bean 定义名称
	GetBeanDefinitionNames() []string
	// GetBeanDefinitionCount 获取bean 定义总数
	GetBeanDefinitionCount() int
	// GetRegistryType 获取注册表类型｜作用域
	GetRegistryType() Scoop
}

type DefaultBeanDefinitionRegistry struct {
	beanDefinitionMap cmap.ConcurrentMap[string, BeanDefinition]
	count             int
	registryType      Scoop
}

func (receiver *DefaultBeanDefinitionRegistry) RegisterBeanDefinition(name string, beanDefinition BeanDefinition) {
	receiver.beanDefinitionMap.Set(name, beanDefinition)
	receiver.count = receiver.count + 1
}

func (receiver *DefaultBeanDefinitionRegistry) RemoveBeanDefinition(name string) *BeanDefinition {
	v := receiver.beanDefinitionMap.Remove(name)
	if v != nil {
		receiver.count = receiver.count - 1
		return &v
	} else {
		return nil
	}
}

func (receiver *DefaultBeanDefinitionRegistry) GetBeanDefinition(name string) *BeanDefinition {
	v, ok := receiver.beanDefinitionMap.Get(name)
	if ok {
		return &v
	} else {
		return nil
	}
}

func (receiver *DefaultBeanDefinitionRegistry) ContainsBeanDefinition(name string) bool {
	return receiver.beanDefinitionMap.Has(name)
}

func (receiver *DefaultBeanDefinitionRegistry) IsBeanDefinitionOverridable(name string) bool {
	return true
}

func (receiver *DefaultBeanDefinitionRegistry) IsBeanNameInUse(name string) bool {
	return receiver.beanDefinitionMap.Has(name)
}

func (receiver *DefaultBeanDefinitionRegistry) GetBeanDefinitionNames() []string {
	return receiver.beanDefinitionMap.Keys()
}

// GetBeanDefinitionCount 获取注册表数量
func (receiver *DefaultBeanDefinitionRegistry) GetBeanDefinitionCount() int {
	return receiver.count
}

// GetRegistryType 获取注册表类型
func (receiver *DefaultBeanDefinitionRegistry) GetRegistryType() Scoop {
	return receiver.registryType
}

// NewBeanDefinitionRegistry 创建bean 定义注册表
func NewBeanDefinitionRegistry(scope Scoop) BeanDefinitionRegistry {
	return &DefaultBeanDefinitionRegistry{
		beanDefinitionMap: cmap.New[BeanDefinition](),
		count:             0,
		registryType:      scope,
	}
}
